package org.internna.expensetracker.model;

import java.util.Set;
import java.util.HashSet;
import javax.persistence.OneToMany;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.validation.constraints.NotNull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.internna.expensetracker.model.Subcategory;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;

@RooEntity
@RooJavaBean
@RooToString
public class Category implements Comparable<Category> {

	private static final Log logger = LogFactory.getLog(Category.class);

    @NotNull
    private String category;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parentCategory", cascade = CascadeType.REMOVE)
    private Set<Subcategory> subcategories = new HashSet<Subcategory>();

    @NotNull
    private Boolean income;

    public Boolean isIncome() {
    	return getIncome();
    }

    public static final Category findByCategory(String category) {
    	try {
	    	return entityManager().createQuery("select c from Category c where c.category = :category", Category.class)
	        		.setParameter("category", category)
	        		.getSingleResult();
    	} catch (RuntimeException re) {
    		logger.warn("Category [" + category + "] not found in database (" + re.getMessage() + ")");
    		return null;
    	}
    }

	@Override public int compareTo(Category other) {
		return other == null
				? -1 
				: income == null
					? 1
					: income.compareTo(other.income) == 0
						? category.compareTo(other.category)
						: income.compareTo(other.income);
	}

}
